package org.dfrt.own.controller;

import com.github.pagehelper.PageInfo;
import org.dfrt.own.entity.BlogExp;
import org.dfrt.own.entity.User;
import org.dfrt.own.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author zhang
 * ClassName: BlogController
 * Description: 博客控制器
 * date: 2023/10/6 17:54
 * @since JDK 8
 */
@Controller
@RequestMapping("/blog")
public class BlogController {

    //规定一下每页显示几条数据
    private static final int PAGE_SIZE = 6;

    @Autowired
    private BlogService blogService;

    /**
     * 查找当前用户的博客文章，分页展示
     *
     * @param page
     * @return
     */
    @RequestMapping("/split_user")
    public String split_user(Integer page, HttpSession session, HttpServletRequest request) {

        if (page == null) {
            page = 1;
        }

        User user = (User) session.getAttribute("user");

        user.setPage((page-1)*6);

        List<BlogExp> blogExps = blogService.findBlogSplitPageByUser(user);
        Integer sunp = blogService.findBlogSumPage();
        int sum = 0;
        if (sunp % 6 == 0) {
            sum = sunp / 6;
        } else {
            sum = sunp / 6 + 1;
        }

        for (BlogExp blog:
             blogExps) {
            System.out.println(blog);
        }

        request.setAttribute("sum", sum);
        request.setAttribute("page", page);
        request.setAttribute("blogs", blogExps);

        return "MyBlog";
    }

    @RequestMapping("/split_blog")
    public String split_blog(Integer page, Model model) {

        if (page == null) {
            page = 1;
        }

        PageInfo pageInfo = blogService.findBlogSplitPage(page, PAGE_SIZE);

        model.addAttribute("blogs", pageInfo);

        return "allblog";
    }

    /**
     * 上传博客文章
     *
     * @param session
     * @param btitle
     * @param bcontent
     * @return
     */
    @RequestMapping("/pblog")
    public String pblog(HttpSession session, String btitle, String bcontent) {
        User user = (User) session.getAttribute("user");

        int i = blogService.pubBlog(user, btitle, bcontent);

        if (i > 0) {
            return "forward:/blog/split_user.action";
        }

        return "pubblog";
    }

    @RequestMapping("/deleblog")
    public String deleblog(Integer bid) {
        int i = blogService.deleBlog(bid);
        return "redirect:/blog/split_user.action";
    }
}
